import { useState, useCallback } from 'react';
import { message } from 'antd';
import { loginService } from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';

export default function useTeacher() {
  const [teacher, setTeacher] = useState(null);

  const login = useCallback(async (values: any, props) => {
    const res = await loginService.login(values).catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('登录成功');
      sessionStorage.setItem('Authorization', `Bearer ${res?.data.token}`);
      setTeacher(res?.data.teacherInfo);
      setTimeout(() => {
        props.history.push("/index/userInfo");
      }, 500);
    })
  }, []);

  const logout = useCallback(async () => {
    const res = await loginService.logout().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('登出成功');
      sessionStorage.removeItem('Authorization');
      setTeacher(null);
    })
  }, []);

  return {
    teacher,
    setTeacher,
    login,
    logout
  };
}
